import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import styles from './index.less';
import CSSModules from 'react-css-modules';
import {
  List,
  Card,
  Row,
  Col,
  Button,
  Icon,
  BackTop,
  Avatar,
  Anchor,
  Affix,
} from 'antd';
import {Link} from 'react-router-dom';

import PageHeader from 'ant-design-pro/lib/PageHeader';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import VehicleModel from './addVehicleModel';

const ButtonGroup = Button.Group;
import myaxios, {get, put, post, deleteAxios} from 'common/fetch';

import {GET_BRAND_URL} from 'constant/url';
import {openPanel} from '@bizfe/biz-rc-panel';

import {UPLOAD_URL, ARTICLE_URL} from 'constant/url';

// 引入编辑器以及编辑器样式
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/braft.css';

class BrandList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      brandLetters: [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'V',
        'W',
        'X',
        'Y',
        'Z',
      ],
      noDataLetters: [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'V',
        'W',
        'X',
        'Y',
        'Z',
      ],
      loading: false,
      brandListA: [],
      brandListB: [],
      brandListC: [],
      brandListD: [],
      brandListE: [],
      brandListF: [],
      brandListG: [],
      brandListH: [],
      brandListI: [],
      brandListG: [],
      brandListK: [],
      brandListL: [],
      brandListM: [],
      brandListN: [],
      brandListO: [],
      brandListP: [],
      brandListQ: [],
      brandListR: [],
      brandListS: [],
      brandListT: [],
      brandListV: [],
      brandListW: [],
      brandListX: [],
      brandListY: [],
      brandListZ: [],
    };
  }
  componentDidMount() {
    this.fetchData('A');
    window.addEventListener('scroll', this.handleScroll);
  }
  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
  }
  updateState = obj => {
    const postDetail = {...this.state.postDetail, ...obj};

    this.setState({
      postDetail,
    });
  };
  hidePanel = () => {
    this.panelObj.close();
  };
  setClassification() {
    alert('1');
    let currentIndex = 800;
    const config = {
      customClass: styles['.biz-panel'],
      marginLeft: 200,
      top: '0',
      theme: '',
      leftCloseAble: true,
      // titleAble: true,
      title: '设置分类',
      content: <carfication />,
      buttonsAble: false,
      buttons: [
        {
          value: '确定',
          isSubmit: true,
        },
        {
          value: '取消',
        },
      ],
      onBeforeClose: function() {
        //me.getMsgList(me.getQuery());
        return true;
      },
      onCancelFunc: function() {
        return true;
      },
      submitFunc: function(closeFunc) {
        closeFunc();
      },
      zIndex: currentIndex,
    };
    this.panelObj = openPanel(config, document.body);
  }
  fetchData = capital => {
    if (this.state.loading) {
      return false;
    }
    this.setState({
      loading: true,
    });
    return get(GET_BRAND_URL, {
      capital,
    }).then(res => {
      const brandCapital = `brandList${capital}`;
      const capitalIndex = this.state.noDataLetters.indexOf(capital);
      this.state.noDataLetters.splice(capitalIndex, 1);
      this.setState({
        [brandCapital]: res,
        loading: false,
      });
    });
  };
  handleScroll = () => {
    const {noDataLetters} = this.state;
    const scrollHeight = window.pageYOffset;
    const windowHeight = document.body.clientHeight;
    const showHeight = scrollHeight + windowHeight;
    noDataLetters.map(item => {
      const refNow = ReactDOM.findDOMNode(this[`brandListRef${item}`]);
      const refNowHeight = refNow.offsetTop;
      if (refNowHeight > showHeight || refNowHeight < scrollHeight - 120) {
        return false;
      } else if (
        !(
          this.state[`brandList${item}`] &&
          this.state[`brandList${item}`].length > 0
        )
      ) {
        this.fetchData(item);
      }
    });
  };
  addVehicleModel = () => {
    let currentIndex = 800;
    const config = {
      customClass: styles['.biz-panel'],
      marginLeft: 200,
      top: '0',
      theme: '',
      leftCloseAble: true,
      // titleAble: true,
      title: '设置分类',
      content: (
        <VehicleModel
          modelDetail={this.state.modelDetail}
          reloadModelDetail={this.getModelDetail}
          hidePanel={this.hidePanel}
        />
      ),
      buttonsAble: false,
      buttons: [
        {
          value: '确定',
          isSubmit: true,
        },
        {
          value: '取消',
        },
      ],
      onBeforeClose: function() {
        //me.getMsgList(me.getQuery());
        return true;
      },
      onCancelFunc: function() {
        return true;
      },
      submitFunc: function(closeFunc) {
        closeFunc();
      },
      zIndex: currentIndex,
    };
    this.panelObj = openPanel(config, document.body);
  };
  quickSearch = async capital => {
    if (
      this.state[`brandList${capital}`] &&
      this.state[`brandList${capital}`].length > 0
    ) {
      const brandLetter = document.getElementById(`brand${capital}`);
      brandLetter && brandLetter.scrollIntoView();
    } else {
      let rel = await this.fetchData(capital);
      const brandLetter = document.getElementById(`brand${capital}`);
      brandLetter && brandLetter.scrollIntoView();
    }
  };
  render() {
    const {match} = this.props;
    const {brandLetters} = this.state;
    return (
      <div>
        <PageHeader
          title="品牌列表"
          action={
            <Button type="primary" onClick={this.addVehicleModel.bind(this)}>
              <Icon />新建车型
            </Button>
          }
          content="所有品牌列表"
          breadcrumbList={[
            {
              title: '车库',
            },
          ]}
          linkElement={Link}
          className={styles.pageHeader}
        />
        <div className={`${styles.content} ${styles['home-container']}`}>
          <BackTop />
          <Affix offsetTop={-24}>
            <Card
              style={{margin: 24, boxShadow: '1px 1px 2px 1px #eee'}}
              bordered={false}>
              <Row type="flex" justify="start">
                <Col span={2}>快速定位:</Col>
                <Col>
                  <ButtonGroup>
                    {brandLetters.map((letter, index) => (
                      <Button
                        key={index}
                        size="small"
                        onClick={() => {
                          this.quickSearch(letter);
                        }}>
                        {letter}
                      </Button>
                    ))}
                  </ButtonGroup>
                </Col>
              </Row>
            </Card>
          </Affix>
          <div ref={ele => (this.brandListRef = ele)}>
            {brandLetters.length > 0 &&
              brandLetters.map((capList, index) => {
                return (
                  <Card
                    style={{margin: 24, marginTop: 0}}
                    bordered={false}
                    className={styles.cardList}
                    title={capList}
                    id={`brand${capList}`}
                    name={`brand${capList}`}
                    ref={ele => (this[`brandListRef${capList}`] = ele)}>
                    <List
                      rowKey="name"
                      split={true}
                      itemLayout="vertical"
                      dataSource={this.state[`brandList${capList}`]}
                      renderItem={(item, index) => (
                        <List.Item key={index}>
                          <List.Item.Meta
                            title={
                              <span>
                                {item.name}&nbsp;&nbsp;&nbsp;<img
                                  src={item.url}
                                  height={50}
                                  align="absmiddle"
                                />
                              </span>
                            }
                          />
                          <List
                            rowKey="id"
                            grid={{gutter: 12, lg: 6, md: 3, sm: 2, xs: 1}}
                            dataSource={item.modelList}
                            renderItem={item => (
                              <List.Item>
                                <Link
                                  to={`${match.path}/model/${item.id || '-1'}`}>
                                  <Card
                                    className={styles.card}
                                    hoverable
                                    bodyStyle={{
                                      padding: '6px 3px',
                                      textAlign: 'center',
                                    }}>
                                    {item.modelName}
                                  </Card>
                                </Link>
                              </List.Item>
                            )}
                          />
                        </List.Item>
                      )}
                    />
                  </Card>
                );
              })}
          </div>
        </div>
      </div>
    );
  }
}

export default CSSModules(BrandList, styles);
